#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.dev'

import django
django.setup()

import time, hashlib, base64, json, requests, datetime, openpyxl
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import algorithms
from random import Random
from Crypto.Cipher import AES
import urllib.parse
from decimal import Decimal
from random import randint
from requests_toolbelt.multipart.encoder import MultipartEncoder

from users.models import Level, User, CustomerUser
from merchants.models import *
from activities.models import Activity, ActivityLevel, ActivityLevelRecord, ActivityData, PointRecord, Channel
from goods.models import *
from orders.models import *
from equity_mall.utils.qiniu_storage import pic_upload
from speeds.models import SpeedLoanDraw
from cashbonus.models import CashActivityData, CashActivityDataKeguan, CashActivity, CashActivityKeguanRecords
from vouchers.models import AliDiscountCouponInfo, AliActivity, AliDiscountCouponInfoKeguan, AliDiscountCouponKeguanRecords


def get_sign(data_dict, secret):
    params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False)
    params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list) + '&secret=' + secret
    md5 = hashlib.md5()
    md5.update(params_str.encode('utf-8'))
    sign = md5.hexdigest().upper()
    return sign


def haizhui_get_sign(data_dict, secret):
    params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False)
    params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list) + '&appSecret=' + secret
    md5 = hashlib.md5()
    md5.update(params_str.encode('utf-8'))
    sign = md5.hexdigest().upper()
    return sign


def pkcs7_padding(data):
    if not isinstance(data, bytes):
        data = data.encode()
    padder = padding.PKCS7(algorithms.AES.block_size).padder()
    padded_data = padder.update(data) + padder.finalize()
    return padded_data


def encrypt(text, key, iv):
    key = key.encode('utf-8')
    iv = iv.encode('utf-8')
    mode = AES.MODE_CBC
    cryptos = AES.new(key, mode, iv)
    text = pkcs7_padding(text.encode('utf-8'))
    cipher_text = cryptos.encrypt(text)
    return base64.b64encode(cipher_text).decode('utf-8')


def decrypt(text, key, iv):
    key = key.encode('utf-8')
    iv = iv.encode('utf-8')
    text = base64.b64decode(text.encode('utf8'))
    mode = AES.MODE_CBC
    cryptor = AES.new(key, mode, iv)
    plain_text = cryptor.decrypt(text)
    return bytes.decode(plain_text).rstrip('\0').rstrip("\x01").rstrip("\x02").rstrip("\x03").rstrip("\x04").rstrip("\x05").rstrip("\x06").rstrip("\x07").rstrip("\x08").rstrip("\x09").rstrip("\x0a").rstrip("\x0b").rstrip("\x0c").rstrip("\x0d").rstrip("\x0e").rstrip("\x0f").rstrip("\x10")


def random_str(randomlength=32):
    strs = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        strs += chars[random.randint(0, length)]
    return strs


def get_result(method, body, token):
    key = 'cw8jYudat!fHKnLkpsTm^VJ&5PylBMW7'
    iv = 'acOtV2Bb3QZIJYdR'
    secret = 'Alp$muNw&dT3RPy1onDsMkG86hBOYLDf'
    # token = 'imden eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2Nzc4NzI4MjMsImlhdCI6MTY3NzgyOTYyMywidXNlcklkIjoiMjM4NDAzMTYyODQxNzUxNzA4In0.-IsscKZvjqHSdRLoCF2QfhBgvQLHP9HQDiEg2DUu8gg'
    timestamp = str(int(time.time()))
    nonce = random_str()
    data_dict = {'method': method}
    data = encrypt(json.dumps(body).replace(' ', ''), key, iv)
    data_dict['data'] = data
    data_dict['nonce'] = nonce
    data_dict['timestamp'] = timestamp
    signture = get_sign(data_dict, secret)
    headers = {
        'company-token': token,
        'sign-app-nonce': nonce,
        'sign-app-signture': signture,
        'sign-app-timestamp': timestamp
    }
    url = f'https://i.wxmas.com/company-gateway/api?data={urllib.parse.quote(data)}&method={method}'
    response = requests.get(url=url, headers=headers)
    return decrypt(response.json()['data'], key, iv)


def post_result(method, body, token):
    key = 'cw8jYudat!fHKnLkpsTm^VJ&5PylBMW7'
    iv = 'acOtV2Bb3QZIJYdR'
    secret = 'Alp$muNw&dT3RPy1onDsMkG86hBOYLDf'
    # token = 'imden eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2Nzc4NzI4MjMsImlhdCI6MTY3NzgyOTYyMywidXNlcklkIjoiMjM4NDAzMTYyODQxNzUxNzA4In0.-IsscKZvjqHSdRLoCF2QfhBgvQLHP9HQDiEg2DUu8gg'
    timestamp = str(int(time.time()))
    nonce = random_str()
    data_dict = {'method': method}
    data = encrypt(json.dumps(body).replace(' ', ''), key, iv)
    data_dict['data'] = data
    data_dict['nonce'] = nonce
    data_dict['timestamp'] = timestamp
    signture = get_sign(data_dict, secret)
    headers = {
        'company-token': token,
        'sign-app-nonce': nonce,
        'sign-app-signture': signture,
        'sign-app-timestamp': timestamp,
        'content-type': 'application/json'
    }
    url = 'https://i.wxmas.com/company-gateway/api'
    response = requests.post(url=url, headers=headers, data=json.dumps({'data': data, 'method': method}))
    return decrypt(response.json()['data'], key, iv)


def get_user_by_code(method, body):
    # key = 'l8pB8OJy6wXtl3eD5HewSXwLDvX9PfGI'
    # iv = 'B6sWd7h8SvcpS85a'
    # secret = 'LyovsTrFKJmJXV0fUWga3YkQgwtGOi9H'
    # appId = 'imapFpCQAJPm9Ghpi0fO'
    key = 'x17jweJfs2peeGUsTdcRR6pNgZmARMIm'
    iv = 'scQG8UlQ3RGkCk4q'
    secret = '9s2LV99FGzoUjR0eRYii2scGX46WcE8l'
    appId = 'imapQPtHDERnbiYSrACi'
    timestamp = str(int(time.time()))
    nonce = random_str()
    data_dict = {'method': method}
    data = encrypt(json.dumps(body).replace(' ', ''), key, iv)
    data_dict['data'] = data
    data_dict['nonce'] = nonce
    data_dict['appId'] = appId
    data_dict['timestamp'] = timestamp
    signture = get_sign(data_dict, secret)
    headers = {
        'Sign-App-Id': appId,
        'Sign-App-Nonce': nonce,
        'Sign-App-Signture': signture,
        'Sign-App-Timestamp': timestamp,
        'content-type': 'application/json'
    }
    url = 'https://equity.wxmas.com/equitygateway/api'
    response = requests.post(url=url, headers=headers, data=json.dumps({'data': data, 'method': method}))
    return decrypt(response.json()['data'], key, iv)


def get_user_coupon_state(method, body):
    # key = 'l8pB8OJy6wXtl3eD5HewSXwLDvX9PfGI'
    # iv = 'B6sWd7h8SvcpS85a'
    # secret = 'LyovsTrFKJmJXV0fUWga3YkQgwtGOi9H'
    # appId = 'imapFpCQAJPm9Ghpi0fO'
    key = 'x17jweJfs2peeGUsTdcRR6pNgZmARMIm'
    iv = 'scQG8UlQ3RGkCk4q'
    secret = '9s2LV99FGzoUjR0eRYii2scGX46WcE8l'
    appId = 'imapQPtHDERnbiYSrACi'
    timestamp = str(int(time.time()))
    nonce = random_str()
    data_dict = {'method': method}
    data = encrypt(json.dumps(body).replace(' ', ''), key, iv)
    data_dict['data'] = data
    data_dict['nonce'] = nonce
    data_dict['appId'] = appId
    data_dict['timestamp'] = timestamp
    signture = get_sign(data_dict, secret)
    headers = {
        'Sign-App-Id': appId,
        'Sign-App-Nonce': nonce,
        'Sign-App-Signture': signture,
        'Sign-App-Timestamp': timestamp,
        'content-type': 'application/json'
    }
    # url = 'http://equitytest.shangyi.pro/equitygateway/api'
    url = 'https://equity.wxmas.com/equitygateway/api'
    print(body)
    print(data)
    response = requests.post(url=url, headers=headers, data=json.dumps({'data': data, 'method': method}))
    print(response.json())
    return decrypt(response.json()['data'], key, iv)


def login_post_result(method, body):
    key = 'cw8jYudat!fHKnLkpsTm^VJ&5PylBMW7'
    iv = 'acOtV2Bb3QZIJYdR'
    secret = 'Alp$muNw&dT3RPy1onDsMkG86hBOYLDf'
    # token = 'imden eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2Nzc4NzI4MjMsImlhdCI6MTY3NzgyOTYyMywidXNlcklkIjoiMjM4NDAzMTYyODQxNzUxNzA4In0.-IsscKZvjqHSdRLoCF2QfhBgvQLHP9HQDiEg2DUu8gg'
    timestamp = str(int(time.time()))
    nonce = random_str()
    data_dict = {'method': method}
    data = encrypt(json.dumps(body).replace(' ', ''), key, iv)
    data_dict['data'] = data
    data_dict['nonce'] = nonce
    data_dict['timestamp'] = timestamp
    signture = get_sign(data_dict, secret)
    headers = {
        # 'company-token': token,
        'sign-app-nonce': nonce,
        'sign-app-signture': signture,
        'sign-app-timestamp': timestamp,
        'content-type': 'application/json'
    }
    url = 'https://i.wxmas.com/company-gateway/api'
    response = requests.post(url=url, headers=headers, data=json.dumps({'data': data, 'method': method}))
    return decrypt(response.json()['data'], key, iv)


def login_qrcode_result(method, body):
    key = 'X7ALsOPM09ZeyJTUfHGcnuqb5QmNjx3R'
    iv = 'JlrwG2XYCy4AHOx9'
    secret = 'RNfDp7n3eWGmP1LiHxTzqv5YK96S8BQb'
    token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2ODQ3NDMzOTIsImp0aSI6IjI2NzM1MDIzNzM3NzcxMTQ4MCIsImlhdCI6MTY4NDczNjE5MiwiTmFtZSI6IumSn-eBtuaIkCIsIkNoYW5uZWxpZCI6ImltcWRPd3d6YlBOSnFTZGtVVVczIiwiQXBwaWQiOiJ3eGVhYTcxMjA4YzFjN2E0MjMiLCJPcGVuaWQiOiJvaFpMVDRpaHFPb19OT2NIMFdhdjRQZUpXNFkwIiwiTW9iaWxlIjoiMTM1MTA1MzUyNjUiLCJJc1NpbmdsZSI6dHJ1ZSwiSXNTdXBlciI6dHJ1ZSwiT3JnSWQiOiIiLCJTdGFmZkNvbW1vbklkIjoiIn0.iUdSuilLSRXnUepeVFnP6Mx9kq3sYBqUVfUwhaaEorE'
    timestamp = str(int(time.time()))
    nonce = random_str()
    data_dict = {'method': method}
    data = encrypt(json.dumps(body).replace(' ', ''), key, iv)
    data_dict['data'] = data
    data_dict['nonce'] = nonce
    data_dict['timestamp'] = timestamp
    signture = get_sign(data_dict, secret)
    headers = {
        'Authorization': token,
        'sign-app-nonce': nonce,
        'sign-app-signture': signture,
        'sign-app-timestamp': timestamp,
        'content-type': 'application/json'
    }
    url = 'https://ministaff.wxmas.com/mini-staff-gateway/api'
    response = requests.post(url=url, headers=headers, data=json.dumps({'data': data, 'method': method}))
    return decrypt(response.json()['data'], key, iv)


def pull_ri_companyuser():
    print('%s: pull_ri_companyuser' % time.ctime())
    method = 'companyUserList'
    page = 1
    is_break = 0
    while True:
        body = {"page": str(page), 'pageSize': '1000'}
        if is_break:
            break
        result = json.loads(get_result(method, body))['data']['manageList']
        if not result:
            break
        for i in result:
            user_data = {}
            user_data['wyh_id'] = i['id']
            user_data['username'] = i['name']
            user_data['nickname'] = i['name']
            user_data['mobile'] = i['phone']
            user_data['platform'] = 2
            user_data['role_id'] = 3
            user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
            if i['isUse']:
                user_data['is_active'] = 1
            else:
                user_data['is_active'] = 0
            try:
                level = Level.objects.filter(orgId=i['orgIds'][0]).first()
                user_data['OrgId'] = i['orgIds'][0]
                if level:
                    user_data['level_id'] = level.id
            except:
                pass
            user_data['account'] = i['jobNumber']
            try:
                instance, create = User.objects.get_or_create(mobile=user_data['mobile'], defaults=user_data)
                if create:
                    print(instance.id)
            except:
                print(i['phone'])
        page += 1


def pull_ri_merchant():
    print('%s: pull_ri_merchant' % time.ctime())
    method = 'SupplierList'
    # body = {"page": '1', 'pageSize': '10'}
    # print(post_result(method, body))
    is_break = 0
    page = 1
    while True:
        body = {"page": str(page), 'pageSize': '1000'}
        print(body)
        if is_break:
            break
        result = json.loads(get_result(method, body))['data']['list']
        if not result:
            break
        for i in result:
            user_data = {}
            enter_data = {}
            enter_data['id'] = i['id']
            user_data['name'] = i['name']
            user_data['managerName'] = i['managerName']
            user_data['managermobile'] = i['managerMobile']
            user_data['wyfMerchantID'] = i['wyfMerchantID']
            user_data['ruiyinxinMerchantID'] = i['ruiyinxinMerchantID']
            enter_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
            user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')

            try:
                instance, create = Merchant.objects.get_or_create(wyfMerchantID=str(user_data['wyfMerchantID']), defaults=user_data)
                if create:
                    print(instance.id)
                enter_data['merchant_id'] = instance.id
                try:
                    level = Level.objects.filter(orgId=i['orgID']).first()
                    enter_data['OrgId'] = i['orgID']
                    if level:
                        enter_data['level_id'] = level.id
                except:
                    pass
                enter, create = MerchantEnter.objects.get_or_create(merchant_id=enter_data['merchant_id'], level_id=enter_data['level_id'], defaults=enter_data)
            except Exception as e:
                print(i['managerMobile'])
        page += 1


def pull_merchant(wyfMerchantID):
    print('%s: pull_ri_merchant' % time.ctime())
    method = 'SupplierList'
    # body = {"page": '1', 'pageSize': '10'}
    # print(post_result(method, body))
    body = {"page": '1', 'pageSize': '1', "ruiyinxinMerchantID": wyfMerchantID}
    result = json.loads(get_result(method, body))['data']['list']
    i = result[0]
    user_data = {}
    enter_data = {}
    enter_data['id'] = i['id']
    user_data['name'] = i['name']
    user_data['managerName'] = i['managerName']
    user_data['managermobile'] = i['managerMobile']
    user_data['wyfMerchantID'] = i['wyfMerchantID']
    user_data['ruiyinxinMerchantID'] = i['ruiyinxinMerchantID']
    enter_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
    user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
    instance, create = Merchant.objects.get_or_create(wyfMerchantID=str(user_data['wyfMerchantID']), defaults=user_data)
    if create:
        print(instance.id)
    enter_data['merchant_id'] = instance.id
    try:
        level = Level.objects.filter(orgId=i['orgID']).first()
        enter_data['OrgId'] = i['orgID']
        if level:
            enter_data['level_id'] = level.id
    except:
        pass
    enter, create = MerchantEnter.objects.get_or_create(merchant_id=enter_data['merchant_id'], level_id=enter_data['level_id'], defaults=enter_data)
    return instance


def pull_ri_activity():
    print('%s: pull_ri_activity' % time.ctime())
    method = 'GiftBagPointGetActivityList'
    # body = {"page": '1', 'pageSize': '1'}
    # print(get_result(method, body))
    is_break = 0
    page = 1
    while True:
        if is_break:
            break
        body = {"page": str(page), 'pageSize': '100'}
        result = json.loads(get_result(method, body))['data']['activityList']
        if not result:
            break
        for i in result:
            user_data = {}
            user_data['activity_id'] = i['id']
            user_data['name'] = i['name']
            user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
            user_data['platform'] = 2
            user_data['available_begin_time'] = i['timeRule']['startedAt'].replace('T', ' ').replace('+08:00', '')
            user_data['available_end_time'] = i['timeRule']['endedAt'].replace('T', ' ').replace('+08:00', '')
            user_data['max_point'] = i['totalPoint']
            user_data['distributed_point'] = i['receivePoint']
            try:
                level = Level.objects.filter(orgId=i['orgId']).first()
                user_data['OrgId'] = i['orgId']
                if level:
                    level.point += int(i['totalPoint'])
                    level.save()
                    user_data['level_id'] = level.id
            except:
                pass
            try:
                user = User.objects.filter(orgId=i['wyh_id']['userId']).first()
                if user:
                    user_data['create_user_id'] = user.id
                else:
                    user_id=None
            except:
                user_id=None
            try:
                instance, create = Activity.objects.update_or_create(activity_id=user_data['activity_id'], defaults=user_data)
                if create:
                    print(instance.id)
                    activity_level = ActivityLevel.objects.create(
                        level_id=instance.level_id,
                        activity_id=instance.id,
                        max_point=instance.max_point
                    )
                    ActivityLevelRecord.objects.create(
                        activity_level_id=activity_level.id,
                        point=activity_level.max_point,
                        operation_type=1,
                        user_id=user_id,
                        create_time=i['createdAt'].replace('T', ' ').replace('+08:00', ''),
                        level_id=instance.level_id,
                    )
                # else:
                #     is_break = 1
                #     break
            except:
                print(i['name'])
        page += 1


def pull_point_record():
    print('%s: pull_point_record' % time.ctime())
    method = 'GiftBagPointGetAllotRecordList'
    body = {"page":"1","pageSize":"10","source":"allot","actId":"282101128651489280","orgId":"176044761152262144"}
    dict1 = {
        '282101128651489280': '176044765266874368',
        '282447815928848384': '176044766097346560',
        '283529454674829312': '176044766932013056',
        '282447848145043456': '176044766932013056',
        '283678692142538752': '176044767766679552',
        '282447876406517760': '176044767766679552',
        '282447906336817152': '176044768601346048',
        '282447716901330944': '176044764428013568',
        '282447951018991616': '207904418933768192',
        '282447768390352896': '176044765266874368'
    }
    print(get_result(method, body))
    result = json.loads(get_result(method, body))['data']['recordList']
    for i in result[::-1]:
        activitylevel_data = {}
        level = Level.objects.get(orgId=dict1[i['id']])
        activitylevel = ActivityLevel.objects.filter(activity_id=44, level_id=level.id).first()
        parent_activitylevel = ActivityLevel.objects.filter(activity_id=44, level_id=level.parent_id).first()
        if activitylevel:
            activitylevel.max_point -= Decimal(i['point'])
            activitylevel.remain_point -= Decimal(i['point'])
            activitylevel.save()
        else:
            activitylevel_data['level_id'] = level.id
            activitylevel_data['activity_id'] = 44
            activitylevel_data['max_point'] = -Decimal(i['point'])
            activitylevel_data['remain_point'] = -Decimal(i['point'])
            activitylevel = ActivityLevel.objects.create(**activitylevel_data)
        parent_activitylevel.max_point += Decimal(i['point'])
        parent_activitylevel.remain_point += Decimal(i['point'])
        parent_activitylevel.save()
        ActivityLevelRecord.objects.create(
            activity_level_id=parent_activitylevel.id,
            point=-Decimal(i['point']),
            operation_type=2,
            remain_point=parent_activitylevel.remain_point,
            user_id=38,
            create_time=i['operatedAt'].replace('T', ' ').replace('+08:00', ''),
            level_id=parent_activitylevel.level_id,
            remark=i['remark']
        )
        ActivityLevelRecord.objects.create(
            activity_level_id=activitylevel.id,
            point=-Decimal(i['point']),
            operation_type=1,
            remain_point=activitylevel.remain_point,
            user_id=38,
            create_time=i['operatedAt'].replace('T', ' ').replace('+08:00', ''),
            level_id=activitylevel.level_id,
            remark=i['remark']
        )

    # query_set = ActivityLevel.objects.all()
    # for instance in query_set:
    #     level = instance.level
    #     body = {"page": "1", "pageSize": "10", "source": "allot", "actId": "282101895965851648", "orgId": level.orgId}
    #     result = json.loads(get_result(method, body))['data']['recordList']


def pull_user(openId):
    print('%s: pull_ri_user' % time.ctime())
    method = 'MemberList'
    body = {"page": '1', 'pageSize': '1', 'openId': openId}
    # print(get_result(method, body))
    result = json.loads(get_result(method, body))['data']['list'][0]
    user_data = {}
    # user_data['user_id'] = i['Id']
    user_data['mobile'] = result['Mobile']
    user_data['old_openid'] = result['Openid']
    user_data['is_distributor'] = result['isDistributor']
    user_data['idcode'] = result['idcode']
    user_data['realname'] = result['realname']
    user_data['username'] = result['nickname']
    user_data['address'] = result['address']
    user_data['is_offline'] = result['offlineMember']
    user_data['point'] = result['localpoint']
    user_data['avatar'] = result['avatar']
    user_data['create_time'] = result['CreatedAt'].replace('T', ' ').replace('+08:00', '')
    instance, create = CustomerUser.objects.update_or_create(mobile=user_data['mobile'], defaults=user_data)
    return instance


def pull_manageruser(mobile):
    print('%s: pull_manageruser' % time.ctime())
    method = 'companyUserList'
    body = {"page": '1', 'pageSize': '1', "mobile": mobile}
    result = json.loads(get_result(method, body))['data']['manageList'][0]
    user_data = {}
    user_data['wyh_id'] = result['id']
    user_data['username'] = result['name']
    user_data['nickname'] = result['name']
    user_data['mobile'] = result['phone']
    user_data['platform'] = 2
    user_data['role_id'] = 3
    user_data['create_time'] = result['createdAt'].replace('T', ' ').replace('+08:00', '')
    if result['isUse']:
        user_data['is_active'] = 1
    else:
        user_data['is_active'] = 0
    try:
        level = Level.objects.filter(orgId=result['orgIds'][0]).first()
        user_data['OrgId'] = result['orgIds'][0]
        if level:
            user_data['level_id'] = level.id
    except:
        pass
    user_data['account'] = result['jobNumber']
    instance, create = User.objects.get_or_create(mobile=user_data['mobile'], defaults=user_data)
    return instance


def pull_ri_activity_data():
    print('%s: pull_ri_activity_data' % time.ctime())
    method = 'GiftBagPointGetActivityReceiveList'
    body = {"page": '1', 'pageSize': '1000', "actId": "282101128651489280","openid":"oI_D75aXxwdjXNATn3-xSt9WYt30"}
    receiveList = json.loads(get_result(method, body))['data']['receiveList']
    for i in receiveList[::-1]:
        print(i)
        if i['status'] == 'normal':
            user_data = {}
            user_data['activity_data_id'] = i['id']
            user_data['point'] = i['point']
            user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
            user_data['received_time'] = i['receivedAt'].replace('T', ' ').replace('+08:00', '')
            user_data['activity_id'] = 44
            user_data['old_openid'] = i['openId']
            user_data['phone'] = i['marketerMobile']
            try:
                riuser = CustomerUser.objects.filter(old_openid=i['openId']).first()
                if riuser:
                    user_data['customer_user_id'] = riuser.id
                else:
                    riuser = pull_user(i['openId'])
                    user_data['customer_user_id'] = riuser.id
            except:
                pass
            try:
                user = User.objects.filter(mobile=i['marketerMobile']).first()
                user_data['phone'] = i['marketerMobile']
                if user:
                    user_data['companyuser_id'] = user.id
                else:
                    user = pull_manageruser(i['marketerMobile'])
                    user_data['companyuser_id'] = user.id
            except:
                pass
            try:
                level = Level.objects.filter(orgId=i['marketerOrgId']).first()
                user_data['OrgId'] = i['marketerOrgId']
                if level:
                    user_data['level_id'] = level.id
                    try:
                        activity_level = ActivityLevel.objects.filter(level_id=level.id, activity_id=44).first()
                        if activity_level:
                            user_data['activity_level_id'] = activity_level.id
                    except:
                        pass
            except:
                pass
            try:
                instance, create = ActivityData.objects.update_or_create(activity_data_id=user_data['activity_data_id'], defaults=user_data)
                if create:
                    instance = ActivityData.objects.get(id=instance.id)
                    print(instance.id)
                    try:
                        riuser = CustomerUser.objects.filter(old_openid=i['openId']).first()
                        if riuser and not riuser.level_id:
                            riuser.level_id = instance.level_id
                        riuser.point+=instance.point
                        riuser.save()
                    except:
                        pass
                    activity_level = instance.activity_level
                    if activity_level:
                        activity_level.take_point += instance.point
                        activity_level.remain_point -= instance.point
                        activity_level.save()
                        ActivityLevelRecord.objects.create(
                            activity_level_id=activity_level.id,
                            point=instance.point,
                            operation_type=3,
                            remain_point=activity_level.remain_point,
                            user_id=user.id,
                            create_time=instance.create_time,
                            customer_user_id=riuser.id,
                            remark='领取邮米'
                        )
                        PointRecord.objects.create(
                            customer_user_id=riuser.id,
                            create_time=instance.create_time,
                            operate_type=1,
                            business_type=1,
                            point=instance.point,
                            point_balance=riuser.point,
                            activity_data_id=instance.id
                        )
            except Exception as e:
                print(i['id'])
    # activity_set = RIActivity.objects.filter(platform=1)
    # for activity in activity_set:
    #     page = 1
    #     is_break = 0
    #     while True:
    #         if is_break:
    #             break
    #         body = {"page": str(page), 'pageSize': '1000', "actId": activity.activity_id}
    #         print(body)
    #         result = json.loads(get_result(method, body))['data']['receiveList']
    #         if not result:
    #             break
    #         for i in result:
    #             user_data = {}
    #             user_data['activity_data_id'] = i['id']
    #             user_data['point'] = i['point']
    #             user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
    #             user_data['received_time'] = i['receivedAt'].replace('T', ' ').replace('+08:00', '')
    #             user_data['activity_id'] = activity.id
    #             user_data['openId'] = i['openId']
    #             user_data['phone'] = i['marketerMobile']
    #             try:
    #                 riuser = RIUser.objects.filter(openid=i['openId']).first()
    #                 if riuser:
    #                     user_data['riuser_id'] = riuser.id
    #             except:
    #                 pass
    #             try:
    #                 level = Level.objects.filter(orgId=i['marketerOrgId']).first()
    #                 user_data['OrgId'] = i['marketerOrgId']
    #                 if level:
    #                     user_data['level_id'] = level.id
    #                     if level.level == 1:
    #                         prov_id = level.id
    #                         city_id = None
    #                         district_id = None
    #                         branch_id = None
    #                     elif level.level == 2:
    #                         prov_id = level.parent.id
    #                         city_id = level.id
    #                         district_id = None
    #                         branch_id = None
    #                     elif level.level == 3:
    #                         prov_id = level.parent.parent.id
    #                         city_id = level.parent.id
    #                         district_id = level.id
    #                         branch_id = None
    #                     else:
    #                         prov_id = level.parent.parent.parent.id
    #                         city_id = level.parent.parent.id
    #                         district_id = level.parent.id
    #                         branch_id = level.id
    #                     user_data['prov_id'] = prov_id
    #                     user_data['city_id'] = city_id
    #                     user_data['district_id'] = district_id
    #                     user_data['branch_id'] = branch_id
    #                     try:
    #                         riuser = RIUser.objects.filter(openid=i['openId']).first()
    #                         if riuser and not riuser.level_id:
    #                             riuser.prov_id = prov_id
    #                             riuser.city_id = city_id
    #                             riuser.district_id = district_id
    #                             riuser.branch_id = branch_id
    #                             riuser.level_id = level.id
    #                             riuser.save()
    #                     except:
    #                         pass
    #             except:
    #                 pass
    #             try:
    #                 instance, create = RIActivityData.objects.update_or_create(activity_data_id=user_data['activity_data_id'], defaults=user_data)
    #                 if create:
    #                     print(instance.id)
    #                 else:
    #                     is_break = 1
    #                     break
    #             except:
    #                 print(i['id'])
    #         page += 1


def pull_goods():
    print('%s: pull_ri_goods' % time.ctime())
    method = 'GoodsList'
    # body = {"page": '1', 'pageSize': '1'}
    # print(get_result(method, body))
    page = 1
    is_break = 0
    while True:
        if is_break:
            break
        body = {"page": str(page), 'pageSize': '100'}
        print(body)
        result = json.loads(get_result(method, body))['data']['list']
        if not result:
            break
        for i in result:
            if i['exchangeNumber']:
                user_data = {}
                user_data['id'] = i['id']
                user_data['name'] = i['name']
                user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
                user_data['equityID'] = i['equityID']
                user_data['point'] = i['exchangeNumber']
                default_image = f'youhuiquanyi/{i["supplierDetail"]["wyfMerchantID"]}/default_image{i["equityID"]}.png'
                pic_upload(requests.get(i['images'][0]['url']).content, key=default_image)
                user_data['default_image'] = default_image
                user_data['desc_detail'] = i['detail']
                user_data['category_id'] = 1
                try:
                    merchant = Merchant.objects.filter(wyfMerchantID=str(i["supplierDetail"]["wyfMerchantID"])).first()
                    if merchant:
                        user_data['merchant_id'] = merchant.id
                    else:
                        merchant = pull_merchant(wyfMerchantID=i["supplierDetail"]["wyfMerchantID"])
                        user_data['merchant_id'] = merchant.id
                except:
                    pass
                if not i['isSale']:
                    is_launched = 0
                else:
                    is_launched = 1
                try:
                    instance, create = Goods.objects.update_or_create(id=user_data['id'], defaults=user_data)
                    if create:
                        print(instance.id)
                        level = Level.objects.filter(orgId=i['orgId']).first()
                        if level:
                            LaunchedGoods.objects.create(
                                name=instance.name,
                                caption=instance.caption,
                                goods=instance,
                                category_id=1,
                                point=instance.point,
                                is_launched=is_launched,
                                level=level,
                                create_time=instance.create_time
                            )
                        GoodsImage.objects.create(
                            goods=instance,
                            image=instance.default_image
                        )
                except Exception as e:
                    print(e)
                    print(i['name'])
        page += 1


def write_excel_xlsx(path, sheet_name, value):
    index = len(value)
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    sheet.title = sheet_name
    for i in range(0, index):
        for j in range(0, len(value[i])):
            sheet.cell(row=i + 1, column=j + 1, value=str(value[i][j]))
    workbook.save(path)


def check_file(stock_id, business_no_list):
    print('%s: check_file' % time.ctime())
    l1 = ['商户号']
    l2 = []
    l2.append(l1)
    file_url = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), f'static/{stock_id}可用商户.xlsx')
    sheet_name_xlsx = 'Sheet1'
    for business_no in business_no_list:
        l3 = [business_no]
        l2.append(l3)
    write_excel_xlsx(file_url, sheet_name_xlsx, l2)
    token = Channel.objects.get(id=5).cookie
    staff_id = Channel.objects.get(id=5).ecc_csrf_token

    method = 'GetListWithChannelId'
    body = {"page":"1","pageSize":"10","stockId":f"{stock_id}","specialType":"WX_VOUCHER"}
    result = json.loads(get_result(method, body, token))
    print(result)
    if not result['data']['equities']:
        return {'data':{'successNum':0}}

    time.sleep(5)

    method = 'GetTempSecretKey'
    body = {"configId":"91227289022377666","fileName":f"{stock_id}可用商户.xlsx","filePath":"fileImport","usedAt":"2023-03-01T15:04:33+08:00"}
    result = json.loads(get_result(method, body, token))
    print(result)
    fileId = result['data']['fileId']
    body = {
        "Key": result['data']['fileKey'],
        "Signature": result['data']['cosConfig']['authorization']['token'],
        "file": (f'{stock_id}可用商户.xlsx', open(file_url, 'rb')),
    }
    multipart_encoder = MultipartEncoder(body)
    headers = {}
    headers['Content-Type'] = multipart_encoder.content_type
    response = requests.post(result['data']['uploadUrl'], data=multipart_encoder, headers=headers)
    time.sleep(30)
    method = 'UploadEnd'
    body = {"id": fileId}
    result = json.loads(get_result(method, body, token))
    time.sleep(30)
    method = 'ImportSubmit'
    body = {"type":"coupon-merchant-import", "fileId":fileId, 'additionalData': '{"channel_id":"imqdOwwzbPNJqSdkUUW3","isSuper":true,"staff_id":"' + f'{staff_id}' + '","stock_no":"' + f'{stock_id}' + '","business_no":""}'}
    result = json.loads(post_result(method, body, token))
    if result['meta']['code'] != 200:
        return {'data':{'successNum':0}}
    jobId = result['data']['id']
    method = 'ImportStatus'
    body = {"type":"coupon-merchant-import", "fileId": '', 'additionalData': '{"channel_id":"imqdOwwzbPNJqSdkUUW3","isSuper":true,"staff_id":"' + f'{staff_id}' + '","stock_no":"' + f'{stock_id}' + '","business_no":""}'}
    result = json.loads(get_result(method, body, token))
    if result['meta']['code'] != 200:
        return {'data':{'successNum':0}}
    print(result)
    time.sleep(30)
    method = 'ImportVerify'
    body = {"status":"VERIFY_SUCCESS", "jobId": jobId}
    print(body)
    result = json.loads(post_result(method, body, token))
    print(result)
    time.sleep(30)
    a = 1
    while True:
        if a > 30:
            break
        method = 'ImportStatus'
        body = {"type":"coupon-merchant-import", "fileId": '', 'additionalData': '{"channel_id":"imqdOwwzbPNJqSdkUUW3","isSuper":true,"staff_id":"' + f'{staff_id}' + '","stock_no":"' + f'{stock_id}' + '","business_no":""}'}
        result = json.loads(get_result(method, body, token))
        print(result)
        if result['data']['status'] == 'SUCCESS':
            break
        time.sleep(30)
        a += 1
    return result


def generatespeeddraw():
    for i in range(1, 10001):
        speedloandraw_data = {}
        speedloandraw_data['partner_trade_no'] = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}000000{i}'
        speedloandraw_data['amount'] = 8.8
        speedloandraw_data['desc'] = '极速贷抽奖活动奖励'
        speedloandraw_data['nonce_str'] = random_str()
        speedloandraw_data['gears'] = randint(1, 9)
        speedloandraw_data['payment_status'] = 1
        speedloandraw, create = SpeedLoanDraw.objects.get_or_create(defaults=speedloandraw_data, partner_trade_no=speedloandraw_data['partner_trade_no'])


def wash_goods_remain_stock():
    goods_set = Goods.objects.all()
    for goods in goods_set:
        remain_stock = goods.stock
        launchedgoods_set = goods.launchedgoods_set.all()
        for launchedgoods in launchedgoods_set:
            remain_stock += launchedgoods.stock
        goods.remain_stock = remain_stock
        goods.save()


def wash_applyment_level():
    query_set = GoodsModifyApplyment.objects.all()
    for query in query_set:
        query.level_id = query.companyuser.level_id
        query.save()


def pull_StaffQrcodeStatus():
    print('%s: pull_StaffQrcodeStatus' % time.ctime())
    method = 'StaffQrcodeStatus'
    body = {"no":"2e14124195b3d46967601ba01e68bea8cfa7685c9d4ce1d00d325622c00c1c72"}
    print(login_post_result(method, body))


def pull_StaffQrcodeLogin():
    print('%s: pull_StaffQrcodeLogin' % time.ctime())
    method = 'StaffQrcodeLogin'
    body = {"no":"222a044d64b39453e23fe27497119e40bfce591b6a06181e84e0b6d832a24d1b", "method":"login"}
    print(login_qrcode_result(method, body))


def wash_merchant_bill():
    query_set = MerchantBill.objects.filter(settlement_amount=0, settlement_record_id__isnull=False)
    for query in query_set:
        settlement_record = query.settlement_record
        query.settlement_amount = settlement_record.amount
        query.channel_id = settlement_record.channel_id
        query.save()
        print(query.id)


def wash_merchantsettlementrecord():
    query_set = MerchantSettlementRecord.objects.filter(level_id__isnull=True)
    for query in query_set:
        query.level_id = query.merchant.level_id
        query.save()
        print(query.id)


def pull_activity_level():
    print('%s: pull_activity_level' % time.ctime())
    method = 'GiftBagCouponGetAllotList'
    body = {"actId":"489740144020008960","orgId":"176044855754788864"}
    token = 'imden eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MDE5NjAyMzIsImlhdCI6MTcwMTkxNzAzMiwidXNlcklkIjoiMjY3MzUwMjM3Mzc3NzExNDgwIn0.ISB8D4t0HnlpkrNXlyhHLLiiiaADH99hXRwmfjJN1Hk'
    print(get_result(method, body, token))
    # page = 1
    # is_break = 0
    # while True:
    #     if is_break:
    #         break
    #     body = {"page": str(page), 'pageSize': '100'}
    #     print(body)
    #     result = json.loads(get_result(method, body))['data']['list']
    #     if not result:
    #         break
    #     for i in result:
    #         if i['exchangeNumber']:
    #             user_data = {}
    #             user_data['id'] = i['id']
    #             user_data['name'] = i['name']
    #             user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
    #             user_data['equityID'] = i['equityID']
    #             user_data['point'] = i['exchangeNumber']
    #             default_image = f'youhuiquanyi/{i["supplierDetail"]["wyfMerchantID"]}/default_image{i["equityID"]}.png'
    #             pic_upload(requests.get(i['images'][0]['url']).content, key=default_image)
    #             user_data['default_image'] = default_image
    #             user_data['desc_detail'] = i['detail']
    #             user_data['category_id'] = 1
    #             try:
    #                 merchant = Merchant.objects.filter(wyfMerchantID=i["supplierDetail"]["wyfMerchantID"]).first()
    #                 if merchant:
    #                     user_data['merchant_id'] = merchant.id
    #                 else:
    #                     merchant = pull_merchant(wyfMerchantID=i["supplierDetail"]["wyfMerchantID"])
    #                     user_data['merchant_id'] = merchant.id
    #             except:
    #                 pass
    #             if not i['isSale']:
    #                 is_launched = 0
    #             else:
    #                 is_launched = 1
    #             try:
    #                 instance, create = Goods.objects.update_or_create(id=user_data['id'], defaults=user_data)
    #                 if create:
    #                     print(instance.id)
    #                     level = Level.objects.filter(orgId=i['orgId']).first()
    #                     if level:
    #                         LaunchedGoods.objects.create(
    #                             name=instance.name,
    #                             caption=instance.caption,
    #                             goods=instance,
    #                             category_id=1,
    #                             point=instance.point,
    #                             is_launched=is_launched,
    #                             level=level,
    #                             create_time=instance.create_time
    #                         )
    #                     GoodsImage.objects.create(
    #                         goods=instance,
    #                         image=instance.default_image
    #                     )
    #             except Exception as e:
    #                 print(e)
    #                 print(i['name'])
    #     page += 1


def ylx_api(method, body):
    # key = 'l8pB8OJy6wXtl3eD5HewSXwLDvX9PfGI'
    # iv = 'B6sWd7h8SvcpS85a'
    # secret = 'LyovsTrFKJmJXV0fUWga3YkQgwtGOi9H'
    # appId = 'imapFpCQAJPm9Ghpi0fO'
    key = 'x17jweJfs2peeGUsTdcRR6pNgZmARMIm'
    iv = 'scQG8UlQ3RGkCk4q'
    secret = '9s2LV99FGzoUjR0eRYii2scGX46WcE8l'
    appId = 'imapQPtHDERnbiYSrACi'
    timestamp = str(int(time.time()))
    nonce = random_str()
    data_dict = {'method': method}
    data = encrypt(json.dumps(body).replace(' ', ''), key, iv)
    data_dict['data'] = data
    data_dict['nonce'] = nonce
    data_dict['appId'] = appId
    data_dict['timestamp'] = timestamp
    signture = get_sign(data_dict, secret)
    headers = {
        'Sign-App-Id': appId,
        'Sign-App-Nonce': nonce,
        'Sign-App-Signture': signture,
        'Sign-App-Timestamp': timestamp,
        'content-type': 'application/json'
    }
    # url = 'http://equitytest.shangyi.pro/equitygateway/api'
    url = 'https://equity.wxmas.com/equitygateway/api'
    response = requests.post(url=url, headers=headers, data=json.dumps({'data': data, 'method': method}))
    return json.loads(decrypt(response.json()['data'], key, iv))


def push_keguan_activity_data():
    '''同步数据至客管系统'''
    print('%s: push_keguan_activity_data' % time.ctime())
    today = datetime.datetime.now()
    yesterday = today - datetime.timedelta(1)
    received_time_begin = yesterday.strftime("%Y-%m-%d 00:00:00")
    received_time_end = yesterday.strftime("%Y-%m-%d 23:59:59")
    '''微邮惠礼包'''
    cashactivitydata_set = CashActivityData.objects.filter(received_time__lte=received_time_end, cash_activity__is_keguan=1, state=2, cashactivitydatakeguan__isnull=True)
    for cashactivitydata in cashactivitydata_set:
        cashactivity = cashactivitydata.cash_activity
        received_time = cashactivitydata.received_time.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
        if cashactivitydata.customeruservice_id:
            memberId = cashactivitydata.customeruservice_id
            cstmName = cashactivitydata.customeruservice.realname
            mobileNo = cashactivitydata.customeruservice.mobile
            if cashactivitydata.customeruservice.idcode and '**' not in cashactivitydata.customeruservice.idcode:
                idCard = cashactivitydata.customeruservice.idcode
            else:
                idCard = ''
        else:
            memberId = cashactivitydata.customer_user_id
            cstmName = cashactivitydata.customer_user.realname
            mobileNo = cashactivitydata.customer_user.mobile
            if cashactivitydata.customer_user.idcode and '**' not in cashactivitydata.customer_user.idcode:
                idCard = cashactivitydata.customer_user.idcode
            else:
                idCard = ''
        body = {}
        body['sourceId'] = cashactivity.activity_id
        body['logId'] = cashactivitydata.payment_no
        body['memberId'] = str(memberId)
        body['cstmName'] = cstmName
        body['mobileNo'] = mobileNo
        body['partakeTime'] = received_time
        if idCard:
            body['cardType'] = '10'
            body['idCard'] = idCard
        body['prizeList'] = [
            {
                "awardSeq": cashactivitydata.payment_no,
                "awardType": "03",
                "status": "normal",
                "awardName": cashactivity.name,
                "awardNum": int(cashactivitydata.amount*100),
                "receiveTime": received_time,
            }
        ]
        keguan_result = ylx_api('ThirdActDataSyncGdCrm', body)
        keguan_data = {}
        keguan_data['cashactivitydata_id'] = cashactivitydata.id
        keguan_data['push_status'] = 1
        keguan_data['push_time'] = today
        if keguan_result['meta']['code'] != 200:
            keguan_data['return_msg'] = keguan_result['meta']['msg']
            keguan_data['push_status'] = 2
        CashActivityDataKeguan.objects.update_or_create(defaults=keguan_data, cashactivitydata_id=cashactivitydata.id)

    cashactivitykeguanrecords_set = CashActivityKeguanRecords.objects.filter(cashactivity__is_keguan=0, operate_time__gte=received_time_begin, operate_time__lte=received_time_end, operate_type=2)
    for cashactivitykeguanrecords in cashactivitykeguanrecords_set:
        cashactivity = cashactivitykeguanrecords.cashactivity
        cashactivitydata_set = CashActivityData.objects.filter(received_time__gte=received_time_begin, received_time__lte=received_time_end, cash_activity_id=cashactivity.id, state=2, cashactivitydatakeguan__isnull=True)
        for cashactivitydata in cashactivitydata_set:
            cashactivity = cashactivitydata.cash_activity
            received_time = cashactivitydata.received_time.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
            if cashactivitydata.customeruservice_id:
                memberId = cashactivitydata.customeruservice_id
                cstmName = cashactivitydata.customeruservice.realname
                mobileNo = cashactivitydata.customeruservice.mobile
                if cashactivitydata.customeruservice.idcode and '**' not in cashactivitydata.customeruservice.idcode:
                    idCard = cashactivitydata.customeruservice.idcode
                else:
                    idCard = ''
            else:
                memberId = cashactivitydata.customer_user_id
                cstmName = cashactivitydata.customer_user.realname
                mobileNo = cashactivitydata.customer_user.mobile
                if cashactivitydata.customer_user.idcode and '**' not in cashactivitydata.customer_user.idcode:
                    idCard = cashactivitydata.customer_user.idcode
                else:
                    idCard = ''
            body = {}
            body['sourceId'] = cashactivity.activity_id
            body['logId'] = cashactivitydata.payment_no
            body['memberId'] = str(memberId)
            body['cstmName'] = cstmName
            body['mobileNo'] = mobileNo
            body['partakeTime'] = received_time
            if idCard:
                body['cardType'] = '10'
                body['idCard'] = idCard
            body['prizeList'] = [
                {
                    "awardSeq": cashactivitydata.payment_no,
                    "awardType": "03",
                    "status": "normal",
                    "awardName": cashactivity.name,
                    "awardNum": int(cashactivitydata.amount*100),
                    "receiveTime": received_time,
                }
            ]
            keguan_result = ylx_api('ThirdActDataSyncGdCrm', body)
            keguan_data = {}
            keguan_data['cashactivitydata_id'] = cashactivitydata.id
            keguan_data['push_status'] = 1
            keguan_data['push_time'] = today
            if keguan_result['meta']['code'] != 200:
                keguan_data['return_msg'] = keguan_result['meta']['msg']
                keguan_data['push_status'] = 2
            CashActivityDataKeguan.objects.update_or_create(defaults=keguan_data, cashactivitydata_id=cashactivitydata.id)

    '''代金券'''
    alidiscountcouponinfo_set = AliDiscountCouponInfo.objects.filter(gmt_distributed__lte=received_time_end, alidiscountcoupon__is_keguan=1, status__in=[0, 1, 14, 7], alidiscountcouponinfokeguan__isnull=True)
    for alidiscountcouponinfo in alidiscountcouponinfo_set:
        alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
        partakeTime = alidiscountcouponinfo.gmt_distributed.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
        if alidiscountcouponinfo.customeruservice_id:
            memberId = alidiscountcouponinfo.customeruservice_id
            cstmName = alidiscountcouponinfo.customeruservice.realname
            mobileNo = alidiscountcouponinfo.customeruservice.mobile
            if alidiscountcouponinfo.customeruservice.idcode and '**' not in alidiscountcouponinfo.customeruservice.idcode:
                idCard = alidiscountcouponinfo.customeruservice.idcode
            else:
                idCard = ''
        else:
            memberId = alidiscountcouponinfo.customer_user_id
            cstmName = alidiscountcouponinfo.customer_user.realname
            mobileNo = alidiscountcouponinfo.customer_user.mobile
            if alidiscountcouponinfo.customer_user.idcode and '**' not in alidiscountcouponinfo.customer_user.idcode:
                idCard = alidiscountcouponinfo.customer_user.idcode
            else:
                idCard = ''
        if alidiscountcouponinfo.status == 0:
            status = 'pending'
        elif alidiscountcouponinfo.status == 1:
            status = 'normal'
        elif alidiscountcouponinfo.status == 14:
            status = 'fail'
        else:
            status = 'used'
        prize_data = {
            "awardSeq": alidiscountcouponinfo.out_biz_no,
            "awardType": "05",
            "status": status,
            "awardName": alidiscountcoupon.activity_name,
            "awardNum": int(alidiscountcoupon.amount*100),
            "stockId": alidiscountcoupon.template_id,
            "couponId": alidiscountcouponinfo.voucher_id
        }
        if alidiscountcouponinfo.status == 1:
            prize_data['receiveTime'] = alidiscountcouponinfo.gmt_create.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
        elif alidiscountcouponinfo.status == 7:
            prize_data['receiveTime'] = alidiscountcouponinfo.gmt_create.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
            prize_data['useTime'] = alidiscountcouponinfo.gmt_use.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
        body = {}
        body['sourceId'] = alidiscountcoupon.template_id
        body['logId'] = alidiscountcouponinfo.out_biz_no
        body['memberId'] = str(memberId)
        body['cstmName'] = cstmName
        body['mobileNo'] = mobileNo
        body['partakeTime'] = partakeTime
        if idCard:
            body['cardType'] = '10'
            body['idCard'] = idCard
        body['prizeList'] = [prize_data]
        keguan_result = ylx_api('ThirdActDataSyncGdCrm', body)
        keguan_data = {}
        keguan_data['alidiscountcouponinfo_id'] = alidiscountcouponinfo.id
        keguan_data['push_status'] = 1
        keguan_data['push_time'] = today
        if keguan_result['meta']['code'] != 200:
            keguan_data['return_msg'] = keguan_result['meta']['msg']
            keguan_data['push_status'] = 2
        AliDiscountCouponInfoKeguan.objects.update_or_create(defaults=keguan_data, alidiscountcouponinfo_id=alidiscountcouponinfo.id)

    alidiscountcouponkeguanrecords_set = AliDiscountCouponKeguanRecords.objects.filter(alidiscountcoupon__is_keguan=0, operate_time__gte=received_time_begin, operate_time__lte=received_time_end, operate_type=2)
    for alidiscountcouponkeguanrecords in alidiscountcouponkeguanrecords_set:
        alidiscountcoupon = alidiscountcouponkeguanrecords.cashactivity
        alidiscountcouponinfo_set = AliDiscountCouponInfo.objects.filter(gmt_distributed__gte=received_time_begin, gmt_distributed__lte=received_time_end, alidiscountcoupon_id=alidiscountcoupon.id, status__in=[0, 1, 14, 7], alidiscountcouponinfokeguan__isnull=True)
        for alidiscountcouponinfo in alidiscountcouponinfo_set:
            alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
            partakeTime = alidiscountcouponinfo.gmt_distributed.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
            if alidiscountcouponinfo.customeruservice_id:
                memberId = alidiscountcouponinfo.customeruservice_id
                cstmName = alidiscountcouponinfo.customeruservice.realname
                mobileNo = alidiscountcouponinfo.customeruservice.mobile
                if alidiscountcouponinfo.customeruservice.idcode and '**' not in alidiscountcouponinfo.customeruservice.idcode:
                    idCard = alidiscountcouponinfo.customeruservice.idcode
                else:
                    idCard = ''
            else:
                memberId = alidiscountcouponinfo.customer_user_id
                cstmName = alidiscountcouponinfo.customer_user.realname
                mobileNo = alidiscountcouponinfo.customer_user.mobile
                if alidiscountcouponinfo.customer_user.idcode and '**' not in alidiscountcouponinfo.customer_user.idcode:
                    idCard = alidiscountcouponinfo.customer_user.idcode
                else:
                    idCard = ''
            if alidiscountcouponinfo.status == 0:
                status = 'pending'
            elif alidiscountcouponinfo.status == 1:
                status = 'normal'
            elif alidiscountcouponinfo.status == 14:
                status = 'fail'
            else:
                status = 'used'
            prize_data = {
                "awardSeq": alidiscountcouponinfo.out_biz_no,
                "awardType": "05",
                "status": status,
                "awardName": alidiscountcoupon.activity_name,
                "awardNum": int(alidiscountcoupon.amount*100),
                "stockId": alidiscountcoupon.template_id,
                "couponId": alidiscountcouponinfo.voucher_id
            }
            if alidiscountcouponinfo.status == 1:
                prize_data['receiveTime'] = alidiscountcouponinfo.gmt_create.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
            elif alidiscountcouponinfo.status == 7:
                prize_data['receiveTime'] = alidiscountcouponinfo.gmt_create.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
                prize_data['useTime'] = alidiscountcouponinfo.gmt_use.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
            body = {}
            body['sourceId'] = alidiscountcoupon.template_id
            body['logId'] = alidiscountcouponinfo.out_biz_no
            body['memberId'] = str(memberId)
            body['cstmName'] = cstmName
            body['mobileNo'] = mobileNo
            body['partakeTime'] = partakeTime
            if idCard:
                body['cardType'] = '10'
                body['idCard'] = idCard
            body['prizeList'] = [prize_data]
            keguan_result = ylx_api('ThirdActDataSyncGdCrm', body)
            keguan_data = {}
            keguan_data['alidiscountcouponinfo_id'] = alidiscountcouponinfo.id
            keguan_data['push_status'] = 1
            keguan_data['push_time'] = today
            if keguan_result['meta']['code'] != 200:
                keguan_data['return_msg'] = keguan_result['meta']['msg']
                keguan_data['push_status'] = 2
            AliDiscountCouponInfoKeguan.objects.update_or_create(defaults=keguan_data, alidiscountcouponinfo_id=alidiscountcouponinfo.id)

    '''月月邮免单'''
    waivepaymentmerchant_set = WaivePaymentMerchant.objects.filter(received_time__lte=received_time_end, waivepaymentactivity__is_keguan=1, state=2, waivepaymentmerchantkeguan__isnull=True)
    for waivepaymentmerchant in waivepaymentmerchant_set:
        waivepaymentactivity = waivepaymentmerchant.waivepaymentactivity
        received_time = waivepaymentmerchant.payment_time.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
        memberId = waivepaymentmerchant.merchantuser_id
        cstmName = waivepaymentmerchant.merchantuser.identification_name
        mobileNo = waivepaymentmerchant.merchantuser.mobile
        if waivepaymentmerchant.merchantuser.identification_number and '**' not in waivepaymentmerchant.merchantuser.identification_number:
            idCard = waivepaymentmerchant.merchantuser.identification_number
        else:
            idCard = ''
        body = {}
        body['sourceId'] = f'YYMD{str(waivepaymentactivity.id).zfill(7)}'
        body['logId'] = waivepaymentmerchant.payment_no
        body['memberId'] = str(memberId)
        body['cstmName'] = cstmName
        body['mobileNo'] = mobileNo
        body['partakeTime'] = received_time
        if idCard:
            body['cardType'] = '10'
            body['idCard'] = idCard
        body['prizeList'] = [
            {
                "awardSeq": waivepaymentmerchant.payment_no,
                "awardType": "03",
                "status": "normal",
                "awardName": waivepaymentactivity.activity_name,
                "awardNum": int(waivepaymentmerchant.amount*100),
                "receiveTime": received_time,
            }
        ]
        keguan_result = ylx_api('ThirdActDataSyncGdCrm', body)
        keguan_data = {}
        keguan_data['payment_id'] = waivepaymentmerchant.id
        keguan_data['push_status'] = 1
        keguan_data['push_time'] = today
        if keguan_result['meta']['code'] != 200:
            keguan_data['return_msg'] = keguan_result['meta']['msg']
            keguan_data['push_status'] = 2
        WaivePaymentMerchantKeguan.objects.update_or_create(defaults=keguan_data, payment_id=waivepaymentmerchant.id)

    waivepaymentactivitykeguanrecords_set = WaivePaymentActivityKeguanRecords.objects.filter(cashactivity__is_keguan=0, operate_time__gte=received_time_begin, operate_time__lte=received_time_end, operate_type=2)
    for waivepaymentactivitykeguanrecords in waivepaymentactivitykeguanrecords_set:
        waivepaymentactivity = waivepaymentactivitykeguanrecords.activity
        waivepaymentmerchant_set = WaivePaymentMerchant.objects.filter(payment_time__gte=received_time_begin, payment_time__lte=received_time_end, waivepaymentactivity_id=waivepaymentactivity.id, state=2, waivepaymentmerchantkeguan__isnull=True)
        for waivepaymentmerchant in waivepaymentmerchant_set:
            waivepaymentactivity = waivepaymentmerchant.waivepaymentactivity
            received_time = waivepaymentmerchant.payment_time.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
            memberId = waivepaymentmerchant.merchantuser_id
            cstmName = waivepaymentmerchant.merchantuser.identification_name
            mobileNo = waivepaymentmerchant.merchantuser.mobile
            if waivepaymentmerchant.merchantuser.identification_number and '**' not in waivepaymentmerchant.merchantuser.identification_number:
                idCard = waivepaymentmerchant.merchantuser.identification_number
            else:
                idCard = ''
            body = {}
            body['sourceId'] = f'YYMD{str(waivepaymentactivity.id).zfill(7)}'
            body['logId'] = waivepaymentmerchant.payment_no
            body['memberId'] = str(memberId)
            body['cstmName'] = cstmName
            body['mobileNo'] = mobileNo
            body['partakeTime'] = received_time
            if idCard:
                body['cardType'] = '10'
                body['idCard'] = idCard
            body['prizeList'] = [
                {
                    "awardSeq": waivepaymentmerchant.payment_no,
                    "awardType": "03",
                    "status": "normal",
                    "awardName": waivepaymentactivity.activity_name,
                    "awardNum": int(waivepaymentmerchant.amount * 100),
                    "receiveTime": received_time,
                }
            ]
            keguan_result = ylx_api('ThirdActDataSyncGdCrm', body)
            keguan_data = {}
            keguan_data['payment_id'] = waivepaymentmerchant.id
            keguan_data['push_status'] = 1
            keguan_data['push_time'] = today
            if keguan_result['meta']['code'] != 200:
                keguan_data['return_msg'] = keguan_result['meta']['msg']
                keguan_data['push_status'] = 2
            WaivePaymentMerchantKeguan.objects.update_or_create(defaults=keguan_data, payment_id=waivepaymentmerchant.id)

    '''商户达标'''
    activity_id_list = list(MerchantEightEightActivity.objects.filter(is_keguan=1).values_list('id', flat=True))
    merchanteighteightdraw_set = MerchantEightEightDraw.objects.filter(received_time__lte=received_time_end, activity_id__in=activity_id_list, state=2, merchanteighteightdrawkeguan__isnull=True)
    for merchanteighteightdraw in merchanteighteightdraw_set:
        merchanteighteightactivity = MerchantEightEightActivity.objects.get(id=merchanteighteightdraw.activity_id)
        received_time = merchanteighteightdraw.received_time.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
        if merchanteighteightdraw.merchantuser_id:
            memberId = merchanteighteightdraw.merchantuser_id
            cstmName = merchanteighteightdraw.realname
            mobileNo = merchanteighteightdraw.merchantuser.mobile
            if merchanteighteightdraw.merchantuser.identification_number and '**' not in merchanteighteightdraw.merchantuser.identification_number:
                idCard = merchanteighteightdraw.merchantuser.identification_number
            else:
                idCard = ''
        else:
            memberId = merchanteighteightdraw.mobile
            cstmName = merchanteighteightdraw.realname
            mobileNo = merchanteighteightdraw.mobile
            idCard = ''

        body = {}
        body['sourceId'] = f'SHDB{str(merchanteighteightactivity.id).zfill(7)}'
        body['logId'] = merchanteighteightdraw.payment_no
        body['memberId'] = str(memberId)
        body['cstmName'] = cstmName
        body['mobileNo'] = mobileNo
        body['partakeTime'] = received_time
        if idCard:
            body['cardType'] = '10'
            body['idCard'] = idCard
        body['prizeList'] = [
            {
                "awardSeq": merchanteighteightdraw.payment_no,
                "awardType": "03",
                "status": "normal",
                "awardName": merchanteighteightactivity.name,
                "awardNum": int(merchanteighteightdraw.amount*100),
                "receiveTime": received_time,
            }
        ]
        keguan_result = ylx_api('ThirdActDataSyncGdCrm', body)
        keguan_data = {}
        keguan_data['draw_id'] = merchanteighteightdraw.id
        keguan_data['push_status'] = 1
        keguan_data['push_time'] = today
        if keguan_result['meta']['code'] != 200:
            keguan_data['return_msg'] = keguan_result['meta']['msg']
            keguan_data['push_status'] = 2
        MerchantEightEightDrawKeguan.objects.update_or_create(defaults=keguan_data, draw_id=merchanteighteightdraw.id)

    merchantmightmightactivitykeguanrecords_set = MerchantEightEightActivityKeguanRecords.objects.filter(activity__is_keguan=0, operate_time__gte=received_time_begin, operate_time__lte=received_time_end, operate_type=2)
    for merchantmightmightactivitykeguanrecords in merchantmightmightactivitykeguanrecords_set:
        activity = merchantmightmightactivitykeguanrecords.activity
        merchanteighteightdraw_set = MerchantEightEightDraw.objects.filter(received_time__gte=received_time_begin, received_time__lte=received_time_end, activity_id=activity.id, state=2, merchanteighteightdrawkeguan__isnull=True)
        for merchanteighteightdraw in merchanteighteightdraw_set:
            merchanteighteightactivity = MerchantEightEightActivity.objects.get(id=merchanteighteightdraw.activity_id)
            received_time = merchanteighteightdraw.received_time.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
            if merchanteighteightdraw.merchantuser_id:
                memberId = merchanteighteightdraw.merchantuser_id
                cstmName = merchanteighteightdraw.realname
                mobileNo = merchanteighteightdraw.merchantuser.mobile
                if merchanteighteightdraw.merchantuser.identification_number and '**' not in merchanteighteightdraw.merchantuser.identification_number:
                    idCard = merchanteighteightdraw.merchantuser.identification_number
                else:
                    idCard = ''
            else:
                memberId = merchanteighteightdraw.mobile
                cstmName = merchanteighteightdraw.realname
                mobileNo = merchanteighteightdraw.mobile
                idCard = ''
            body = {}
            body['sourceId'] = cashactivity.activity_id
            body['logId'] = cashactivitydata.payment_no
            body['memberId'] = str(memberId)
            body['cstmName'] = cstmName
            body['mobileNo'] = mobileNo
            body['partakeTime'] = received_time
            if idCard:
                body['cardType'] = '10'
                body['idCard'] = idCard
            body = {}
            body['sourceId'] = f'SHDB{str(merchanteighteightactivity.id).zfill(7)}'
            body['logId'] = merchanteighteightdraw.payment_no
            body['memberId'] = str(memberId)
            body['cstmName'] = cstmName
            body['mobileNo'] = mobileNo
            body['partakeTime'] = received_time
            if idCard:
                body['cardType'] = '10'
                body['idCard'] = idCard
            body['prizeList'] = [
                {
                    "awardSeq": merchanteighteightdraw.payment_no,
                    "awardType": "03",
                    "status": "normal",
                    "awardName": merchanteighteightactivity.name,
                    "awardNum": int(merchanteighteightdraw.amount * 100),
                    "receiveTime": received_time,
                }
            ]
            keguan_result = ylx_api('ThirdActDataSyncGdCrm', body)
            keguan_data = {}
            keguan_data['draw_id'] = merchanteighteightdraw.id
            keguan_data['push_status'] = 1
            keguan_data['push_time'] = today
            if keguan_result['meta']['code'] != 200:
                keguan_data['return_msg'] = keguan_result['meta']['msg']
                keguan_data['push_status'] = 2
            MerchantEightEightDrawKeguan.objects.update_or_create(defaults=keguan_data, draw_id=merchanteighteightdraw.id)





    # print(len(cash_data))


def aaaaaa():
    '''处理阳江大额实物订单'''
    goods_id_list = [30209148,30209148,30209148,30209149,30209148,30209148,30209148,30209149,30209148,30209148,30209148,30209148,30209148,30209148,30209148,30209148,30209148,30209149,30209151,30209150,30209150,30209149,30209148,30209148,30209148,30209148,30209148,30209148,30209148,30209149,30209149,30209151,30209148,30209148,30209149,30209148,30209148,30209148,30209149,30209148,30209148,30209148,30209149,30209148,30209148,30209148,30209148,30209148,30209148,30209149,30209151]
    level_id_list = [8668,8661,8671,8662,8661,8653,8675,8670,8679,8659,8643,8675,8669,8663,8659,8667,8654,8684,8676,8682,8679,8664,8679,8670,8648,8654,8668,8672,8670,8659,8664,8665,8653,8654,8654,8659,8672,8667,8661,8665,8654,8665,8674,8674,8662,8645,8674,8674,8640,8671,8659]
    order_id_list = ["cjhd649544389777240064","cjhd649546357191585792","cjhd649577837175345152","cjhd649668989492023296","cjhd649925352030556160","cjhd649995351571124224","cjhd650298978613415936","cjhd650337409615876096","cjhd650415166089678848","cjhd650651085191364608","cjhd651037401929797632","cjhd651077646771605504","cjhd651093408273977344","cjhd651100942355451904","cjhd651110079038541824","cjhd651131486128623616","cjhd651449658434179072","cjhd651737549580324864","cjhd651826940499775488","cjhd651849685669302272","cjhd652084233624072192","cjhd652088815934746624","cjhd652090821000802304","cjhd652097369315979264","cjhd652453758886047744","cjhd652454947220451328","cjhd652506953356242944","cjhd652533490277249024","cjhd653166624933507072","cjhd653194967816822784","cjhd653612459521126400","cjhd653873805554868224","cjhd654252194992218112","cjhd654252919864455168","cjhd654294802527555584","cjhd654316527906447360","cjhd654396662986825728","cjhd654619996278202368","cjhd654987221648039936","cjhd655068520870076416","cjhd655430433869725696","cjhd655454287920959488","cjhd655723624196112384","cjhd655739871172395008","cjhd655784852650098688","cjhd655793715361251328","cjhd655815226075807744","cjhd655838279308574720","cjhd655872421056380928","cjhd657261194952003584","cjhd658269263735660544"]
    merchant_id = 1954776
    create_time_list = ["2025-02-18 09:37:00","2025-02-18 09:45:00","2025-02-18 11:50:00","2025-02-18 17:52:00","2025-02-19 10:51:00","2025-02-19 15:29:00","2025-02-20 11:35:00","2025-02-20 14:08:00","2025-02-20 19:17:00","2025-02-21 10:55:00","2025-02-22 12:30:00","2025-02-22 15:10:00","2025-02-22 16:12:00","2025-02-22 16:42:00","2025-02-22 17:18:00","2025-02-22 18:44:00","2025-02-23 15:48:00","2025-02-24 10:52:00","2025-02-24 16:47:00","2025-02-24 18:17:00","2025-02-25 09:49:00","2025-02-25 10:08:00","2025-02-25 10:16:00","2025-02-25 10:42:00","2025-02-26 10:18:00","2025-02-26 10:23:00","2025-02-26 13:49:00","2025-02-26 15:35:00","2025-02-28 09:30:00","2025-02-28 11:23:00","2025-03-01 15:02:00","2025-03-02 08:21:00","2025-03-03 09:24:00","2025-03-03 09:27:00","2025-03-03 12:13:00","2025-03-03 13:40:00","2025-03-03 18:58:00","2025-03-04 09:46:00","2025-03-05 10:05:00","2025-03-05 15:28:00","2025-03-06 15:26:00","2025-03-06 17:01:00","2025-03-07 10:51:00","2025-03-07 11:56:00","2025-03-07 14:54:00","2025-03-07 15:30:00","2025-03-07 16:55:00","2025-03-07 18:27:00","2025-03-07 20:42:00","2025-03-11 16:41:00","2025-03-14 11:27:00"]
    reserved_mobile_list = [18826726395,13829830490,13703058082,13922006808,13794772845,13680529597,15113552880,13542617248,18825614821,13450500948,13421266677,13926308757,13680596101,13922015039,13751644231,13421242859,13829871668,13827633889,13632321151,15819165081,18475406958,18316423288,13719862928,13432565579,18926396945,18926325333,13642421988,15819120337,13828872629,13542671067,15728599075,13421229197,18318179370,13078388777,18926307221,13926308808,13719860029,15626457409,15676695957,13924395883,15875175733,13542668381,13537995555,13902528105,13922012833,13421279873,13926305338,13702814981,18998639299,13623078133,15917077441]
    reserved_name_list = ["韩福娣","黄燕锦","麦瑞娇","余雪琳","梁石生","冯祖义","王洁丽","黎月红","杨全端","曾祥禄","龙雪平","章大伟","莫解妹","林进荣","谭起莲","利变","陈谋","孙溪","郑小霞","林喜珠","黎强","范祖艮","李玲玲","曾汝微","欧开宁","高嫦","周计荐","梁超珍","朱剑铎","梁兆豪","陈燕","林链","赵丽仪","梁菊英","陈振安","袁菲","杨国富","贺松华","钟英妥","梁思华","陈广才","张美雄","刘敏","许锡明","杜光战","黎清浓","伍杏仪","关天娣","林德芹","岑应霞","柯琼霞"]
    count = 1
    for i in range(2000):
        goods_id = goods_id_list[i]
        level_id = level_id_list[i]
        order_id = order_id_list[i]
        create_time = create_time_list[i]
        reserved_mobile = reserved_mobile_list[i]
        reserved_name = reserved_name_list[i]
        goods = Goods.objects.get(id=goods_id)
        launchedgoods_id = LaunchedGoods.objects.filter(level_id=level_id, goods_id=goods_id).first().id
        goods_price = goods.price

        customer_user = CustomerUser.objects.filter(mobile=reserved_mobile).first()
        if not customer_user:
            customer_user, create = CustomerUser.objects.get_or_create(mobile=reserved_mobile, defaults={'mobile': reserved_mobile, 'create_time': datetime.datetime.now(), 'realname': reserved_name})

        order_data = {}
        order_data['order_id'] = order_id
        order_data['orderNum'] = order_id
        order_data['create_time'] = create_time
        order_data['total_count'] = count
        order_data['total_price'] = (count * goods_price)
        order_data['total_point'] = (count * goods_price * 100)
        order_data['state'] = 3
        order_data['merchant_id'] = goods.merchant_id
        order_data['payable_amount'] = 0
        order_data['reserved_mobile'] = reserved_mobile
        order_data['order_type'] = 1
        order_data['order_species'] = 1
        order_data['platform'] = 1
        order_data['realpay_amount'] = 1
        order_data['payment_time'] = create_time
        order_data['freight'] = 0
        order_data['payable_settled_amount'] = (count * goods_price)
        order_data['settlement_state'] = 1
        order_data['refund_money'] = 0
        order_data['customer_user_id'] = customer_user.id
        order = OrderInfo.objects.create(**order_data)
        goods = Goods.objects.get(id=goods_id)
        origin_stock = goods.stock
        origin_sales = goods.sales
        origin_remain_stock = goods.remain_stock
        launchedgoods = LaunchedGoods.objects.get(id=launchedgoods_id)
        launched_origin_stock = launchedgoods.stock
        launched_origin_sales = launchedgoods.sales
        launched_new_stock = launched_origin_stock - count
        launched_new_sales = launched_origin_sales + count
        new_sales = origin_sales + count
        new_remain_stock = origin_remain_stock - count
        if not launchedgoods.level_id:
            new_stock = origin_stock - count
        else:
            new_stock = origin_stock
        launched_result = LaunchedGoods.objects.filter(id=launchedgoods_id, stock=launched_origin_stock).update(
            stock=launched_new_stock, sales=launched_new_sales)
        result = Goods.objects.filter(id=goods_id).update(sales=new_sales, remain_stock=new_remain_stock,
                                                          stock=new_stock)
        OrderGoods.objects.create(
            order=order,
            goods=goods,
            count=count,
            price=goods_price,
            merchant_id=goods.merchant_id,
            launched_goods_id=launchedgoods_id
        )


if __name__ == '__main__':
    # pull_activity_level()
    # print(json.loads(get_user_by_code('QueryMemberInfoByCode', {"code": "bb44e903f04691c8c8b8db8ce8c39b92478498c08e649745384a7455ccda6049"})))
    pass
    # print(get_user_by_code('QueryMemberInfoByCode', {"code": '0d0a56d5c422684dc949216707b0688dc1926b0a6322d55abbe7b7b4dd75428b'}))
    # print(get_user_coupon_state('UserCouponState', {"mobile": '13542876256', "equityId": "610132270937944064", "stockNo": "19698491"}))
    # body = {}
    # body['sourceId'] = 'INFLY0001'
    # body['pushEventIds'] = ['3319', ]
    # body['orgNo'] = '440000888'
    # body['activityName'] = '测试活动'
    # body['startTime'] = '2015-05-20T13:29:35.120+08:00'
    # body['endTime'] = '2015-05-20T13:29:35.120+08:00'
    # print(ylx_api('ThirdActInfoSyncGdCrm', body))
    # body = {}
    # body['sourceId'] = 'INFLY0001'
    # body['logId'] = '1'
    # body['memberId'] = '1'
    # body['cstmName'] = '张三'
    # body['mobileNo'] = '13800000000'
    # body['partakeTime'] = '2015-05-20T13:29:35.120+08:00'
    # body['prizeList'] = [
    #     {
    #         "awardSeq": "1",
    #         "awardType": "05",
    #         "status": "normal",
    #         "awardName": "微信代金券",
    #         "receiveTime": "2015-05-20T13:29:35.120+08:00",
    #     }
    # ]
    # print(body)
    # print(ylx_api('ThirdActDataSyncGdCrm', body))
    push_keguan_activity_data()